/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.nhncorp.neptune.changelog;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.nhncorp.neptune.tabletserver.ChangeLog;

public class TransactionData {
  int seq;
  byte[] id;
  ChangeLog[] logList;

  public static TransactionData createFrom(byte[] bytes) throws IOException {
    TransactionData data = new TransactionData();

    ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
    DataInputStream dis = new DataInputStream(bis);

    data.seq = dis.readInt();
    int idLength = dis.readInt();

    if (idLength > 1000000) {
      throw new IOException("id length exceeds million");
    }

    data.id = new byte[idLength];
    dis.readFully(data.id);

    dis.readInt(); // total number of written bytes for change logs

    List<ChangeLog> logList = new ArrayList<ChangeLog>();

    while (true) {
      ChangeLog log = new ChangeLog();

      try {
        log.readFields(dis);
      } catch (EOFException e) {
        break;
      }

      logList.add(log);
    }

    data.logList = logList.toArray(new ChangeLog[0]);

    return data;
  }

  public int getSeqNo() {
    return seq;
  }

  public byte[] getID() {
    return id;
  }

  public int getChangeLogLength() {
    return logList.length;
  }

  public ChangeLog getChangeLogAt(int curLogIndex) {
    return logList[curLogIndex];
  }
}
